import MarkdownIt from 'markdown-it'
import { common, createStarryNight } from '@wooorm/starry-night'
import { toHtml } from 'hast-util-to-html'
import { copyText } from './common'
import { onMounted } from 'vue'
import type { ElementContent } from 'hast'

const markdown = new MarkdownIt()
const starryNight = await createStarryNight(common)
markdown.set({
  highlight: function (value: string, lang: string) {
    const scope = starryNight.flagToScope(lang)
    const codeContent = scope
      ? starryNight.highlight(value, scope).children
      : [{ type: 'text', value }]

    return toHtml({
      type: 'element',
      tagName: 'div',
      properties: { className: ['code-block'] },
      children: [
        // 工具栏
        {
          type: 'element',
          tagName: 'div',
          properties: { className: ['code-toolbar'] },
          children: [
            {
              type: 'element',
              tagName: 'span',
              properties: { className: ['code-language'] },
              children: [{ type: 'text', value: lang || 'text' }]
            },
            {
              type: 'element',
              tagName: 'button',
              properties: {
                className: ['copy-button'],
                'data-clipboard-text': value
              },
              children: [{ type: 'text', value: '复制' }]
            }
          ]
        },
        // 代码块
        {
          type: 'element',
          tagName: 'pre',
          properties: {
            className: scope
              ? [
                  'code',
                  'highlight',
                  'highlight-' + scope.replace(/^source\./, '').replace(/\./g, '-')
                ]
              : ['code']
          },
          children: codeContent as ElementContent[]
        }
      ]
    })
  }
})

onMounted(() => {
  document.addEventListener('click', async evt => {
    const button = (event!.target as HTMLElement).closest('.copy-button')! as HTMLElement
    if (!button || button.classList.contains('copied-feedback')) {
      return
    }
    const text = button.getAttribute('data-clipboard-text')
    if (!text) {
      return
    }
    await copyText(text)
    // 添加视觉反馈
    const originalHTML = button.innerText
    changeButtonText(button, '✅ 已复制')
    button.classList.add('copied-feedback')

    // 2秒后恢复原状
    setTimeout(() => {
      changeButtonText(button, originalHTML)
      button.classList.remove('copied-feedback')
    }, 2000)
  })
})

const changeButtonText = (button: HTMLElement, text: string) => {
  button.style.opacity = '0.2'
  setTimeout(() => {
    button.innerText = text
    button.style.opacity = '1'
  }, 200)
}

export { markdown }
